package com.zlm.spider.util;

import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.springframework.stereotype.Component;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;

import java.util.Properties;

/**
 * @author Harbour
 * @date 2021-04-12 19:33
 */
@Component
public class RedisUtils {
    private static volatile JedisPool jedisPool = null;

    /**
     * 获取http clients 连接池
     * @return 连接池管理
     */
    public static Jedis getJedisClient() {
        if (jedisPool == null) {
            synchronized (RedisUtils.class) {
                if (jedisPool == null) {

                    JedisPoolConfig jedisConfig = new JedisPoolConfig();
                    jedisConfig.setMaxTotal(100); // 最大连接数
                    jedisConfig.setMaxIdle(20); // 最大空闲
                    jedisConfig.setMinIdle(20); // 最大空闲
                    jedisConfig.setBlockWhenExhausted(true); // 忙碌时是否等待
                    jedisConfig.setMaxWaitMillis(5000); // 等待时长
                    jedisConfig.setTestOnBorrow(true); // 每次获取连接进行测试

                    Properties prop = PropertiesUtils.getProperties("application.properties");
                    String host = prop.getProperty("spring.redis.host");
                    int port = Integer.parseInt(prop.getProperty("spring.redis.port"));

                    jedisPool = new JedisPool(jedisConfig, host, port);
                }
            }
        }
        return jedisPool.getResource();
    }

    public static void main(String[] args) {
        Jedis jedisClient = RedisUtils.getJedisClient();
        System.out.println(jedisClient.ping());
        jedisClient.close();
    }
}
